package com.hty.PowerChat;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ToggleButton;

import java.io.File;
import java.util.HashMap;

import pclientbackend.Pclientbackend;
import pclientbackend.ChatClient;

public class LoginActivity extends Activity {

    Button button_login, button_terms, button_login_register;
    EditText editText_id, editText_password;
    ProgressDialog processDialog;
    ToggleButton toggle;
    int count;
    ChatClient chatClient;
    static String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        SharedPreferences SP = getSharedPreferences("userData", MODE_PRIVATE);  // (文件名，操作模式)
        String uname = SP.getString("uname", "");
        editText_id = findViewById(R.id.editText_id);
        editText_id.setText(uname);
        editText_id.setSelection(editText_id.length());
        editText_password = findViewById(R.id.editText_password);
        button_login = findViewById(R.id.button_login);
        button_login_register = findViewById(R.id.button_login_register);
        button_terms = findViewById(R.id.button_terms);
        button_login.setOnClickListener(new ClickListener());
        button_login_register.setOnClickListener(new ClickListener());
        button_terms.setOnClickListener(new ClickListener());
        toggle = findViewById(R.id.toggleButton);
        toggle.setText("");
        toggle.setTextOn("");
        toggle.setTextOff("");
        toggle.setOnCheckedChangeListener(buttonCheckListener);

        editText_id.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
                editText_password.setText("");
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        editText_id.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText_id.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });

        editText_password.setOnFocusChangeListener(new android.view.View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus) {
                    toggle.setVisibility(View.VISIBLE);
                } else {
                    toggle.setVisibility(View.INVISIBLE);
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText_password.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });

    }

    @Override
    public void onResume() {
        super.onResume();
        path = Environment.getExternalStorageDirectory().getPath() + File.separator + "PowerChat";
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        String json = "{\"Host\":\"148.70.58.15:7889\"}";
        chatClient = Pclientbackend.getChatClient(path, json);
        Log.e(Thread.currentThread().getStackTrace()[2] + "", chatClient.getHost());
    }

    class ClickListener implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            int id = v.getId();
            switch (id) {
                case R.id.button_login:
                    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(LoginActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
                    String name = editText_id.getText().toString();
                    String password = editText_password.getText().toString();
                    if(name.equals("")){
                        editText_id.setError("请输入账号");
                        break;
                    }
                    if(password.equals("")){
                        editText_password.setError("请输入密码");
                        break;
                    }

                    processDialog = new ProgressDialog(LoginActivity.this);
                    processDialog.setMessage("登录中......");
                    processDialog.show();
                    count = 0;
                    new Thread(t).start();

                    pclientbackend.UserDataRet userDataRet = chatClient.login(name, password);
                    if (userDataRet != null){
                        Log.e(Thread.currentThread().getStackTrace()[2] + "", userDataRet.toString());
                        SharedPreferences SP = getSharedPreferences("userData", MODE_PRIVATE);  // (文件名，操作模式)
                        SharedPreferences.Editor SPE = SP.edit();
                        SPE.putString("uid", Long.toString(userDataRet.getId()));
                        SPE.putString("uname", userDataRet.getName());
                        SPE.commit();
                        HashMap<String, Object> userData = new HashMap<>();
                        userData.put("id", userDataRet.getId());
                        userData.put("name", userDataRet.getName());
                        userData.put("sex", userDataRet.getSex());
                        userData.put("age", userDataRet.getAge());
                        userData.put("desc", userDataRet.getDesc());
                        userData.put("avatar", R.mipmap.logo);
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.putExtra("user", userData);
                        startActivity(intent);
                    } else {
                        new AlertDialog.Builder(LoginActivity.this).setIcon(R.mipmap.ic_launcher).setTitle("登录失败").setMessage("账号或密码错误，请重新输入。").setPositiveButton("确定", null).show();
                    }
                    break;
                case R.id.button_login_register:
                    startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                    break;
                case R.id.button_terms:
                    Intent intent = new Intent(LoginActivity.this, BrowserActivity.class);
                    intent.putExtra("url", "file:///android_asset/terms.htm");
                    startActivity(intent);
                    break;
            }
        }
    }

    Thread t = new Thread() {
        public void run() {
            try {
                while (count <= 100) {
                    count++;
                    Thread.sleep(10);
                }
                processDialog.cancel();
            } catch (InterruptedException e) {
                processDialog.cancel();
            }
        }
    };

    CompoundButton.OnCheckedChangeListener buttonCheckListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                toggle.setChecked(true);
                toggle.setBackgroundResource(R.mipmap.invisiable);
                editText_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            } else {
                toggle.setChecked(false);
                toggle.setBackgroundResource(R.mipmap.visiable);
                editText_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            }
            int location = editText_password.length();
            editText_password.setSelection(location);
        }
    };

}
